package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.vo.JtPurchaseOrderVo;
import com.ruoyi.business.service.IJtProductService;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.AliSendMessageUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Objects;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.mapper.JtPurchaseOrderMapper;
import com.ruoyi.business.service.IJtPurchaseOrderService;
import com.ruoyi.common.core.text.Convert;

import javax.validation.constraints.NotEmpty;

/**
 * 采购单Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2025-03-29
 */
@Service
public class JtPurchaseOrderServiceImpl implements IJtPurchaseOrderService 
{
    @Autowired
    private JtPurchaseOrderMapper jtPurchaseOrderMapper;
    @Autowired
    private IJtProductService jtProductService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询采购单
     * 
     * @param purchaseId 采购单主键
     * @return 采购单
     */
    @Override
    public JtPurchaseOrder selectJtPurchaseOrderByPurchaseId(Long purchaseId)
    {
        return jtPurchaseOrderMapper.selectJtPurchaseOrderByPurchaseId(purchaseId);
    }

    /**
     * 查询采购单列表
     * 
     * @param jtPurchaseOrder 采购单
     * @return 采购单
     */
    @Override
    public List<JtPurchaseOrder> selectJtPurchaseOrderList(JtPurchaseOrder jtPurchaseOrder)
    {
        return jtPurchaseOrderMapper.selectJtPurchaseOrderList(jtPurchaseOrder);
    }

    /**
     * 新增采购单
     * 
     * @param jtPurchaseOrder 采购单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertJtPurchaseOrder(JtPurchaseOrder jtPurchaseOrder)
    {
        jtPurchaseOrder.setCreateBy(ShiroUtils.getSysUser().getUserName());
        jtPurchaseOrder.setCreateTime(DateUtils.getNowDate());
        int rows = jtPurchaseOrderMapper.insertJtPurchaseOrder(jtPurchaseOrder);
        insertJtPurchaseOrderItem(jtPurchaseOrder);
        return rows;
    }


    /**
     * 修改采购单
     *
     * @param jtPurchaseOrder 采购单
     * @return 结果
     */
    @Override
    public int updateJtPurchaseOrder(JtPurchaseOrder jtPurchaseOrder)
    {
        jtPurchaseOrder.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtPurchaseOrder.setUpdateTime(DateUtils.getNowDate());
        return jtPurchaseOrderMapper.updateJtPurchaseOrder(jtPurchaseOrder);
    }

    /**
     * 修改采购单
     * 
     * @param jtPurchaseOrder 采购单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateJtPurchaseOrder(JtPurchaseOrder jtPurchaseOrder, String removeItemIds)
    {
        jtPurchaseOrder.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtPurchaseOrder.setUpdateTime(DateUtils.getNowDate());
        if(StringUtils.isNotEmpty(removeItemIds)) {
            jtPurchaseOrderMapper.deleteJtPurchaseOrderItemByIds(Convert.toStrArray(removeItemIds));
        }
        updateSaveJtPurchaseOrderItem(jtPurchaseOrder);
        return jtPurchaseOrderMapper.updateJtPurchaseOrder(jtPurchaseOrder);
    }

    public void updateSaveJtPurchaseOrderItem(JtPurchaseOrder jtPurchaseOrder){
        List<JtPurchaseOrderItem> jtPurchaseOrderItemList = jtPurchaseOrder.getJtPurchaseOrderItemList();
        Long purchaseId = jtPurchaseOrder.getPurchaseId();
        if (StringUtils.isNotNull(jtPurchaseOrderItemList))
        {
            List<JtPurchaseOrderItem> list = new ArrayList<>();

            Long totalQty = 0L;
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (JtPurchaseOrderItem orderItem : jtPurchaseOrderItemList)
            {
                if(orderItem.getProductId() == null){
                    throw new BaseException("商品ID不能为空！");
                }
                JtProduct jtProduct = jtProductService.selectJtProductByProductId(orderItem.getProductId());
                if(jtProduct == null){
                    throw new BaseException("商品未找到！");
                }
                if(orderItem.getUnitPrice() == null){
                    throw new BaseException("采购价不能为空！");
                }
                if(orderItem.getQty() == null){
                    throw new BaseException("采购数量不能为空！");
                }
                totalQty += orderItem.getQty();
                orderItem.setAmount(orderItem.getUnitPrice().multiply(new BigDecimal(orderItem.getQty())));
                totalAmount = totalAmount.add(orderItem.getAmount());
                if(orderItem.getItemId() == null) {
                    orderItem.setPurchaseId(purchaseId);
                    orderItem.setCreateTime(DateUtils.getNowDate());
                    orderItem.setCreateBy(ShiroUtils.getSysUser().getUserName());
                    list.add(orderItem);
                } else {
                    jtPurchaseOrderMapper.updateJtPurchaseOrderItem(orderItem);
                }
            }
            if (list.size() > 0)
            {
                jtPurchaseOrderMapper.batchJtPurchaseOrderItem(list);
            }

            jtPurchaseOrder.setTotalQty(totalQty);
            jtPurchaseOrder.setTotalAmount(totalAmount);

            updateJtPurchaseOrder(jtPurchaseOrder);
        }
    }


    /**
     * 批量删除采购单
     * 
     * @param purchaseIds 需要删除的采购单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtPurchaseOrderByPurchaseIds(String purchaseIds)
    {
        jtPurchaseOrderMapper.deleteJtPurchaseOrderItemByPurchaseIds(Convert.toStrArray(purchaseIds));
        return jtPurchaseOrderMapper.deleteJtPurchaseOrderByPurchaseIds(Convert.toStrArray(purchaseIds));
    }

    /**
     * 删除采购单信息
     * 
     * @param purchaseId 采购单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtPurchaseOrderByPurchaseId(Long purchaseId)
    {
        jtPurchaseOrderMapper.deleteJtPurchaseOrderItemByPurchaseId(purchaseId);
        return jtPurchaseOrderMapper.deleteJtPurchaseOrderByPurchaseId(purchaseId);
    }

    /**
     * 新增采购单明细信息
     * 
     * @param jtPurchaseOrder 采购单对象
     */
    public void insertJtPurchaseOrderItem(JtPurchaseOrder jtPurchaseOrder)
    {
        Long totalQty = 0L;
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<JtPurchaseOrderItem> jtPurchaseOrderItemList = jtPurchaseOrder.getJtPurchaseOrderItemList();
        Long purchaseId = jtPurchaseOrder.getPurchaseId();
        if (StringUtils.isNotNull(jtPurchaseOrderItemList))
        {
            List<JtPurchaseOrderItem> list = new ArrayList<>();
            for (JtPurchaseOrderItem jtPurchaseOrderItem : jtPurchaseOrderItemList)
            {
                totalQty += jtPurchaseOrderItem.getQty();
                BigDecimal sub = jtPurchaseOrderItem.getUnitPrice().multiply(new BigDecimal(jtPurchaseOrderItem.getQty()));
                jtPurchaseOrderItem.setAmount(sub);

                totalAmount = totalAmount.add(jtPurchaseOrderItem.getAmount());
                jtPurchaseOrderItem.setPurchaseId(purchaseId);
                jtPurchaseOrderItem.setCreateBy(ShiroUtils.getSysUser().getUserName());
                jtPurchaseOrderItem.setCreateTime(DateUtils.getNowDate());
                list.add(jtPurchaseOrderItem);
            }
            if (list.size() > 0)
            {
                jtPurchaseOrderMapper.batchJtPurchaseOrderItem(list);
            }
        }
        jtPurchaseOrder.setTotalQty(totalQty);
        jtPurchaseOrder.setTotalAmount(totalAmount);

        updateJtPurchaseOrder(jtPurchaseOrder);
    }


    /**
     * 审核 采购单
     * @param ids
     * @return
     */
    @Override
    public int auditJtPurchaseOrderByPurchaseIds(String ids){
        String[] purchaseIds = Convert.toStrArray(ids);
        int rows = jtPurchaseOrderMapper.auditJtPurchaseOrderByPurchaseIds(purchaseIds, ShiroUtils.getSysUser().getUserName(), DateUtils.getNowDate());
        if(rows > 0){
            String sendVal = configService.selectConfigByKey("sys.send.message");
            if("1".equals(sendVal)) {
                sendMessageToSupplier(purchaseIds);
            }
        }
        return rows;
    }

    /**
     * 异步写入  发送短信供应商
     * @param purchaseIds
     */
    private void sendMessageToSupplier(final String[] purchaseIds) {
        if(Objects.isNull(purchaseIds)){
            return;
        }
        threadPoolTaskExecutor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    List<JtPurchaseOrderVo> list = jtPurchaseOrderMapper.selectJtPurchaseOrderVoByPurchaseIds(purchaseIds);
                    for (JtPurchaseOrderVo purchaseOrder : list) {
                        if(purchaseOrder == null || purchaseOrder.getPurchaseId() == null){ continue; }
                        if(StringUtils.isEmpty(purchaseOrder.getSupplierName()) ||
                                StringUtils.isEmpty(purchaseOrder.getOrderNo()) ||
                                StringUtils.isEmpty(purchaseOrder.getPhoneNumber())){

                        }
                        AliSendMessageUtil.supplierPurchaseSendMessage(purchaseOrder.getSupplierName(), purchaseOrder.getOrderNo(), purchaseOrder.getCountryCode() +purchaseOrder.getPhoneNumber());
                        Thread.sleep(10000);
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 反审核 采购单
     * @param ids
     * @return
     */
    @Override
    public int unAuditJtPurchaseOrderByPurchaseIds(String ids){
        String[] purchaseIds = Convert.toStrArray(ids);
        return jtPurchaseOrderMapper.unAuditJtPurchaseOrderByPurchaseIds(purchaseIds, ShiroUtils.getSysUser().getUserName(), DateUtils.getNowDate());
    }

    /**
     * 完成采购单
     * @param ids
     * @return
     */
    @Override
    public int finishedJtPurchaseOrderByPurchaseIds(String ids){
        String[] purchaseIds = Convert.toStrArray(ids);
        return jtPurchaseOrderMapper.finishedJtPurchaseOrderByPurchaseIds(purchaseIds, ShiroUtils.getSysUser().getUserName(), DateUtils.getNowDate());
    }

    /**
     * 查询采购单号
     * @param orderNo
     * @return
     */
    @Override
    public JtPurchaseOrderVo selectJtPurchaseOrderByPurchaseOrderNo(String orderNo){
        return jtPurchaseOrderMapper.selectJtPurchaseOrderByPurchaseOrderNo(orderNo);
    }
}
